package com.ebt.m.commons.mvp;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ebt.m.commons.utils.ActivityUtils;
import com.ebt.m.commons.widgets.BaseRxFragment;

import butterknife.ButterKnife;

/**
 * Created by archer.qi on 2017/3/1.
 */
public abstract class MvpBaseFragment<P extends BasePresenter> extends BaseRxFragment {
    protected P mPresenter;
    protected View mContentView;

    public Activity mContext;
    public Context mApplicationContext;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContentView = inflater.inflate(setContentResource(), container, false);
        ButterKnife.bind(this, mContentView);
        mContext = getActivity();
        if (mContext != null) {
            mApplicationContext = mContext.getApplicationContext();
        }
        mPresenter = createPresenter();
        onFragmentCreate();
        mPresenter.start();
        return mContentView;
    }

    protected abstract P createPresenter();

    protected abstract int setContentResource();

    protected abstract void onFragmentCreate();

    protected abstract void onFragmentDestroy();

    /**
     * default intent to activity
     *
     * @param cls
     */
    protected void launch(Class<?> cls) {
        ActivityUtils.launchActivity(mContext, cls);
    }

    /**
     * intent to activity with data
     *
     * @param cls
     * @param data
     */
    protected void launchWithData(Class<?> cls, Bundle data) {
        ActivityUtils.launchActivity(mContext, cls, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        onFragmentDestroy();
    }

    /**
     * 建议在Activity解除绑定时调用
     */
    public void clearPresenter() {
        mPresenter.onDestroy();
    }
}
